package com.citrinus.feedme;

import com.citrinus.feedme.listener.ShakeListener;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.Log;

public class ShakeDetection implements SensorEventListener {

	private static final String TAG = ShakeDetection.class.getSimpleName();

	private final SensorManager mSensorManager;
	private final Sensor mAccelerometer;
	private long lastUpdate = Long.MAX_VALUE;
	private ShakeListener listener;


	private float last_x;
	private float last_y;
	private float last_z;

	private static final int MAX_SHAKE_DURATION = 1500;

	public ShakeDetection(Context context) {
		mSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
		mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

		last_x = 0;
		last_y = 0;
		last_z = 0;

	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		float[] values = event.values;
		long curTime = System.currentTimeMillis();
		// only allow one update every 100ms.
		if ((curTime - lastUpdate) > 100) {
			long diffTime = (curTime - lastUpdate);

			float x = values[0];
			float y = values[1];
			float z = values[2];

			float speed = Math.abs(x + y + z - last_x - last_y - last_z) / diffTime * 10000;

			if (speed > MAX_SHAKE_DURATION) {
				Log.d("sensor", "shake detected w/ speed: " + speed);
				listener.onShakeListener();
			}
			last_x = x;
			last_y = y;
			last_z = z;
		}
		lastUpdate = curTime;
	}

	public void enableShakeListener() {
		mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
	}

	public void disableShakeListener() {
		mSensorManager.unregisterListener(this);
	}

	public void setListener(ShakeListener listener) {
		this.listener = listener;
		
	}

}
